import random
from verifications import constants
from django import http
from django_redis import get_redis_connection
from django.shortcuts import render
from meiduo_mall.utils.response_code import RET
# Create your views here.
from django.views import View
from meiduo_mall.libs.captcha.captcha import captcha
from verifications import constants

class ImageCodeView(View):
    # 根据前端js代码，构造image_code_id，用于验证码存储和获取
    def get(self,request, image_code_id):
        # 1, 生成图形验证码

        text, image_data = captcha.generate_captcha()

        # 2, 存储图形验证码到redis，进行缓存
        redis_conn = get_redis_connection('code')
        # setex(self, name, time, value)相较于set()多了time
        redis_conn.setex('image_code_%s'%image_code_id, 300, text)
        # 3, 返回响应
        return http.HttpResponse(image_data, content_type='img/png')

class SmsCodeView(View):
    def get(self,request, mobile):
        # 1. 获取图形验证码
        # html 中v-model =image_code
        image_code = request.GET.get('image_code')
        image_code_id = request.GET.get('image_code_id')

        # 2. 校验图形验证码
        # 非空校验
        if not all([image_code, image_code_id]):
            return http.JsonResponse({"errmsg": "参数不全", "code": RET.PARAMERR})
        # 正确性验证（从缓存中读取，判空，判误）
        redis_conn = get_redis_connection('code')
        redis_image_code = redis_conn.get('image_code_%s'%image_code_id)
        if not redis_image_code:
            return http.JsonResponse({"errmsg": "验证码已过期", "code": RET.NODATA})
        # 删除
        redis_conn.delete('image_code_%s'%image_code_id)

        if image_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({"errmsg": "图片验证码错误", "code": RET.DATAERR})

        # 3. 发送短信验证码
        # 验证是否频繁获取验证码
        send_flag = redis_conn.get('sms_code_%s' % mobile)
        # if send_flag:
        #     return http.JsonResponse({"errmsg":"操作过于频繁，请稍候重试", "code":RET.SMSCODERR})

        # 生成验证码并发送
        sms_code = '%06d'% random.randint(0, 999999)

        # 使用celery发送短信
        from celery_tasks.sms_send.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code,constants.REDIS_SMS_CODE_EXPIRES / 60)
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, constants.REDIS_SMS_CODE_EXPIRES / 60], 1)

        #将验证码存入redis缓存
        #使用pipeline管道
        pipe = redis_conn.pipeline()
        pipe.setex('sms_code_%s'%mobile, constants.REDIS_SMS_CODE_EXPIRES, sms_code)
        pipe.setex('send_flag_%s'%mobile, constants.REDIS_SEND_FLAG_EXPIRES, 1)
        pipe.execute()
        print(redis_conn.get('sms_code_%s' % mobile))

        # 4. 返回响应
        return http.JsonResponse({"errmsg": "发送成功", "code": RET.OK})